package com.yunti.yntk.activity.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.widget.LinearLayoutCompat;
import com.alibaba.fastjson.JSONObject;
import com.yunti.yntk.R;
import com.yunti.yntk.activity.BaseActivity;
import com.yunti.yntk.activity.main.MainActivity;
import com.yunti.yntk.api.req.LoginReq;
import com.yunti.yntk.api.res.Verify;
import com.yunti.yntk.manager.NetWorkManager;
import com.yunti.yntk.util.EditTextUtils;
import org.jetbrains.annotations.NotNull;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author yaming
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    ImageView loginbotton;
    EditText username;
    EditText password;
    LinearLayoutCompat loading;
    private boolean pwdCanSee;

    ImageView et_delete_num;
    ImageView et_delete_pwd;

    ImageView et_pwd_see;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public int initLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        loginbotton = findViewById(R.id.loginbutton);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        loading = findViewById(R.id.loading);
        loading.setVisibility(View.GONE);

        et_delete_num = findViewById(R.id.iv_et_num_delete);
        et_delete_pwd = findViewById(R.id.iv_et_pwd_delete);
        et_pwd_see = findViewById(R.id.iv_et_pwd_see);

        loginbotton.setOnClickListener(this);

        //QQ账号输入状态监听
        username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String qq_pwdtext = password.getText().toString().trim();
                String qq_numtext = username.getText().toString().trim();
                if (!TextUtils.isEmpty(qq_numtext) && !TextUtils.isEmpty(qq_pwdtext)) {
                    //如果账号和密码都不为空，打开图片响应事件，并且更换图片
                    loginbotton.setEnabled(true);
                    loginbotton.setImageResource(R.drawable.go_yes);
                } else {
                    loginbotton.setEnabled(false);
                    loginbotton.setImageResource(R.drawable.go_no);
                }
            }
        });

        //QQ密码输入状态监听
        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String qq_pwdtext = password.getText().toString().trim();
                String qq_numtext = username.getText().toString().trim();
                if (!TextUtils.isEmpty(qq_numtext) && !TextUtils.isEmpty(qq_pwdtext)) {
                    //如果账号和密码都不为空，打开图片响应事件，并且更换图片
                    loginbotton.setEnabled(true);
                    loginbotton.setImageResource(R.drawable.go_yes);
                } else {
                    loginbotton.setEnabled(false);
                    loginbotton.setImageResource(R.drawable.go_no);
                }
            }
        });
        //QQ密码输入焦点监听
        password.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                et_pwd_see.setVisibility(View.VISIBLE);
            } else {
                et_pwd_see.setVisibility(View.INVISIBLE);
            }
        });

        //密码可见小图标
        pwdCanSee = false;//true密码可见，false密码不可见
        et_pwd_see.setOnClickListener(v -> {
            if (pwdCanSee) {
                //设置不可见
                password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                et_pwd_see.setImageResource(R.drawable.et_pwd_no);
                password.setSelection(password.getText().length());
                pwdCanSee = false;
            } else {
                //设置可见
                password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                et_pwd_see.setImageResource(R.drawable.et_pwd_yes);
                password.setSelection(password.getText().length());
                pwdCanSee = true;
            }
        });

        //删除小图标
        EditTextUtils.clearButtonListener(username, et_delete_num);
        EditTextUtils.clearButtonListener(password, et_delete_pwd);

        //登录
        //iv_login.setClickable(true);
        //setOnClickListener方法会默认把控件的setClickable设置为true。
        //设置login图片无事件响应
        loginbotton.setEnabled(false);
    }

    @Override
    public void initData() {
        SharedPreferences sp = getSharedPreferences("loginToken", 0);
        String usernamevalue = sp.getString("userName", "");
        //如果name为空，代表未选择保存用户名
        if (!usernamevalue.equals("")) {
            username.setText(usernamevalue);
        }else{
            username.setText("id001");
        }

        String passwordvalue = sp.getString("password", "");
        //如果name为空，代表未选择保存用户名
        if (!passwordvalue.equals("")) {
            password.setText(passwordvalue);
        }else{
            password.setText("yt123456");
        }
    }

    @SuppressLint("HandlerLeak")
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_LONG).show();
                    break;
                case -1:
                    Toast.makeText(LoginActivity.this, "登录失败！", Toast.LENGTH_LONG).show();
                    break;
                case -2:
                    Toast.makeText(LoginActivity.this, "服务器或网络异常！", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.loginbutton) {
            String usernamevalue = username.getText().toString();
            String passwordvalue = password.getText().toString();
            LoginReq loginReq = new LoginReq();
            loginReq.setUsername(usernamevalue);
            loginReq.setPassword(passwordvalue);
            Call<JSONObject> call = NetWorkManager.getRequest().login2(loginReq);
//            LoadingViewManager.with(this).setHintText("加载提示").build();
            loading.setVisibility(View.VISIBLE);
            call.enqueue(new Callback<JSONObject>() {
                //请求成功时回调
                @Override
                public void onResponse(@NotNull Call<JSONObject> call, @NotNull Response<JSONObject> response) {
                    loading.setVisibility(View.GONE);
                    JSONObject jsonObject = response.body();
                    Message msg = new Message();
                    if (jsonObject == null || (Double) jsonObject.get("code") != 200) {
                        msg.what = -1;
                        handler.sendMessage(msg);
                    } else {
                        msg.what = 0;
                        handler.sendMessage(msg);
                        //token保存到本地
                        SharedPreferences sp = getSharedPreferences("loginToken", 0);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("userName", usernamevalue);
                        editor.putString("password", passwordvalue);
                        editor.putString("token", jsonObject.getString("token"));
                        editor.apply();
                        Intent i = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(i);
                        Long userId = jsonObject.getLong("userId");
                        finish();
                    }
                }

                //请求失败时候的回调
                @Override
                public void onFailure(@NotNull Call<JSONObject> call, @NotNull Throwable throwable) {
                    loading.setVisibility(View.GONE);
                    Message msg = new Message();
                    msg.what = -2;
                    handler.sendMessage(msg);
                    Intent i = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(i);
                }
            });
        }
    }

    private void startJWebSClientService(String username) {

    }
}
